<template>
  <div>
    <h3 v-if="formDis" class="title">查看详情</h3>
    <h3 v-else class="title">新增报名</h3>
    <!-- {{ resList }} -->
    <!-- <a href="http://polotrip.msy.cn/<img src=''  onerror='alert(document.cookie)'>" target="_blank" >这是 XSS 的恶意链接</a> -->

    <el-form
      ref="resList"
      :name="resList"
      :model="resList"
      :rules="rules"
      :disabled="formDis"
      label-width="120px"
      class="demo-ruleForm"
      style="margin-top: 20px;">
      <el-form-item label="报名入口名称" prop="name">
        <el-col :span="23" >
          <!-- <span v-html="attack"/><br> -->
          <!-- <span v-html="$xss(attack)"/> -->
          <el-input v-model="resList.name" :disabled="isEdit" maxlength="20" placeholder="请输入报名入口名称, 限制20个字符"/>
        </el-col>
      </el-form-item>
      <el-form-item label="报名介绍" prop="introduction">
        <div style="width:98%">
          <div v-if="formDis" class="tin_box" v-html="$xss(resList.introduction)" />
          <tinymce v-else v-model="resList.introduction" :height="260" :disabled="tinymceDis" />
        </div>
      </el-form-item>
      <el-form-item :class="formDis?'':'add_tip'" label="上传封面图" prop="cost">
        <el-col :span="24" >
          <div style="width:320px" class="fl">
            <div class="thumbnail">
              <img v-show="resList.imgUrl" :src="resList.imgUrl" alt="">
            </div>
            <div v-if="!formDis" class="uploadBox">
              <vueCropper
                :fixed-number="[2,1]"
                :limit="1"
                img-type="slt"
                class="upload-demo fl"
                @modalShowFn="getModalStatus" />
              <el-button v-show="resList.imgUrl" class="btn_clear fr" size="small" type="info" @click="clearPic()">清除</el-button>
              <!-- <p slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/gif文件</p> -->
            </div>
          </div>
        </el-col>
      </el-form-item>
      <el-form-item label="是否推荐" prop="recommendStatus">
        <el-col :span="6" >
          <el-select v-model="resList.recommendStatus">
            <el-option :value="1" label="是"/>
            <el-option :value="0" label="否"/>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item :class="formDis?'':'add_tip'" label="个人信息参数" prop="manageVariableParameters">
        <el-col :span="18" >
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"/>
          <el-checkbox-group v-model="resList.manageVariableParameters" @change="handleCheckedArgumentsChange">
            <el-checkbox v-for="(item, index) in personArgument" :key="index" :label="item.attribute" :value="item" style="width:130px;">{{ item.attribute }}</el-checkbox>
          </el-checkbox-group>
        </el-col>
      </el-form-item>
      <el-form-item style="margin-top:40px;">
        <el-button v-preventReClick type="primary" @click="submitForm('resList')">确定</el-button>
        <el-button v-preventReClick @click="$router.go(-1)">关闭</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import config from '@/utils/config';
import Tinymce from '@/components/Tinymce'
import { GetQiniuToken } from '@/utils/qiniuUpload.js'
import { Message } from 'element-ui'
import mixin from '@/mixin'
// import { provinceAndCityData, regionData, CodeToText, TextToCode } from 'element-china-area-data'
// import { addSaleUser, updateSaleUser } from '@/api/user'
import { getLocalUserName, setLocalUserName } from '@/utils/uid'

import vueCropper from '@/components/cropper'
import UploadImg from '@/components/cropper/uploadImage.vue'
import { addRegistry, getVariableParameters, getRegistryManage } from '@/api/registry'

export default {
  components: { Tinymce, vueCropper, UploadImg },
  mixins: [mixin],
  data() {
    return {
      attack: 'vue is interseting!<img src=x onerror="alert(document.cookie)">',
      resList: {
        name: '',
        introduction: '',
        imgUrl: '',
        recommendStatus: '',
        manageVariableParameters: []
      },
      personArgument: [],
      rules: {
        name: [
          { required: true, message: '报名入口名称', trigger: 'blur' },
          { max: 20, message: '输入字符不得超过20个', trigger: 'blur' }
        //   { pattern: /^[A-z0-9\u4e00-\u9fa5]*$/, message: '不能含有特殊字符', trigger: 'blur' }
        ],
        introduction: [
          { required: true, message: '报名介绍', trigger: 'change' }
          // { max: 100, message: '输入字符不得超过100个', trigger: 'blur' }
        ],
        // imgUrl: [
        //   { required: true, message: '请输入手机号码', trigger: 'blur' },
        //   { validator: validateimgUrl, message: '请输入正确地手机号码', trigger: 'blur' }
        //   // { validator: validateNum, message: '请输入数字', trigger: 'blur' },
        //   // { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值需大于0', trigger: 'blur' }
        // ],
        recommendStatus: [
          { required: true, message: '请选择是否推荐', trigger: 'change' }
          // { validator: validateNum, message: '请输入数字', trigger: 'blur' },
          // { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值需大于0', trigger: 'blur' }
        ]
      },
      isEdit: false,
      fileList: [],
      uploadData: {
        key: '',
        token: ''
      },
      formDis: false,
      tinymceDis: false,

      selectShow: false,
      // 对应<请选择讲师下拉菜单>查询教师信息列表时，把status为1的教师获取出来
      // 选择今天以后的日期
      //   pickerOptions: {
      //     disabledDate(time) {
      //       return time.getTime() < Date.now() - 8.64e7;
      //     }
      //   },
      isDisabled: false,
      allPersonArgument: [],
      checkAll: false,
      isIndeterminate: false
    }
  },
  computed: {
    ruleForm: function() {
      return this.$store.getters.ruleForm
    }
  },
  watch: {
    // ruleForm: {
    //   handler: function(nowVal, oldVal) {
    //     this.$store.dispatch('AddlistenForm', this.ruleForm).then(() => {
    //     }).catch((err) => {
    //       Message.error(err.err)
    //     })
    //   },
    //   deep: true
    // }
  },
  created() {
    console.log('1', this.$xss(this.attack))
    console.log('2', this.attack)
    this.userName = getLocalUserName()
    this.getVariableParametersFn()
    // if (this.userName !== 'admin') this.tinymceDis = true
  },
  mounted() {
    const _self = this;
    // console.log('this.$route.query:', JSON.stringify(this.$route.query))
    // console.log(JSON.parse(_self.$route.query.isEdit))
    if (this.$route.query && JSON.stringify(this.$route.query) !== '{}') {
      console.log('this.$route.query000000:', this.$route.query)
      // const queryData = JSON.parse(this.$route.query)
      // console.log('queryData::::', queryData)
      // this.isEdit = this.$route.query.hasOwnProperty('isEdit') ? JSON.parse(_self.$route.query.isEdit) : false;
      this.formDis = Boolean(this.$route.query.isLook)
      console.log('this.$route.query111111:', this.$route.query.data)
      this.getRegistryManageFn(this.$route.query.data.id)
      // this.resList = this.$route.query.data
    //   if (this.isEdit) {
    //     // 如果是编辑页面，把路由参数带给resList
    //     this.resList = this.$route.query
    //   }
    }
  },
  methods: {
    // 全选按钮
    handleCheckAllChange(val) {
      this.resList.manageVariableParameters = val ? this.allPersonArgument : [];
      this.isIndeterminate = false;
    },
    handleCheckedArgumentsChange(value) {
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.allPersonArgument.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.allPersonArgument.length;
    },
    // 查询报名管理详情
    getRegistryManageFn(id) {
      getRegistryManage({ id }).then(res => {
        console.log('查询报名管理详情:', res)
        if (res.code === '200') {
          this.resList = res.data
          const obj = Object.assign([], this.resList.manageVariableParameters)
          const arr = []
          console.log(obj)
          obj.forEach(item => {
            arr.push(item.attribute)
          })
          this.resList.manageVariableParameters = arr
        }
      })
    },
    // 查询所有可变参数
    getVariableParametersFn() {
      getVariableParameters().then(res => {
        console.log(res)
        if (res.code === '200') {
          this.personArgument = res.data
          res.data.forEach(item => {
            this.allPersonArgument.push(item.attribute)
          })
        }
      })
    },
    clearPic() {
      this.resList.imgUrl = ''
    },
    getModalStatus(url) {
      this.resList.imgUrl = ''
      this.resList.imgUrl = url
    },
    replaceInput(value) {
      console.log('🥕')
      this.resList.name = this.validForbid(value)
    },
    resetForm(formName) {
      this.resList = {
        name: '',
        introduction: '',
        imgUrl: '',
        province: '',
        city: '',
        county: ''
      }
      // this.options = regionData
      this.$refs[formName].clearValidate()
      // this.$refs.form.clearValidate(formName)
    },
    // 省市
    // handleChange(value) {
    //   this.resList.province = value[0]
    //   this.resList.city = value[1]
    //   this.resList.county = value[2]
    //   //  console.log('1:', this.resList.province, this.resList.city)
    //   console.log(this.resList.province, this.resList.city, this.resList.county)
    // },
    request(data) {
      if (this.isEdit) { // 编辑
        // console.log('1-->', data)
        // // 因姓名不能修改， 传参时去掉名字字段
        // delete data.name
        // // 去掉创建时间字段
        // // delete data.createTime
        // console.log('2-->', data)
        // this.loading = true
        // updateSaleUser(data).then(response => {
        //   console.log(data)
        //   if (Number(response.code) === 200) {
        //     Message.success('编辑成功')
        //     this.$router.push('manage');
        //   } else {
        //     Message.error(response.message + '-' + response.data)
        //   }
        // })
      } else { // 新增
        addRegistry(data).then(response => {
          console.log('正在新增')
          if (Number(response.code) === 200) {
            Message.success('新增成功')
            this.$router.go(-1);
          } else {
            Message.error(response.message + '-' + response.data)
          }
        });
      }
    },
    // 把个人信息可选参数数据格式转为后台格式
    filterManageVariableParameters(resList) {
      const list = Object.assign({}, resList)
      const resListArr = resList.manageVariableParameters
      console.log(resListArr, resListArr.length)
      console.log(this.personArgument, this.personArgument.length)
      const objarr = []
      for (let i = 0; i < this.personArgument.length; i++) {
        for (let j = 0; j < resListArr.length; j++) {
          console.log(this.personArgument[i].attribute, '====', resListArr[j])
          if (this.personArgument[i].attribute === resListArr[j]) {
            objarr.push(this.personArgument[i])
          }
        }
      }
      list.manageVariableParameters = objarr
      return list
      // console.log(objarr)
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
        //   if (this.resList.introduction === '') {
        //     Message.error('请填写报名入口介绍')
        //     return
        //   }
          if (this.resList.imgUrl === '') {
            Message.error('请上传图片')
            return
          }
          if (!this.resList.manageVariableParameters.length) {
            Message.error('请选择个人信息参数')
            return
          }
          // console.log(this.resList)
          const list = this.filterManageVariableParameters(this.resList)
          this.request(list)
        } else {
          this.validateError()
          return false;
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.el-checkbox+.el-checkbox{
    margin-left:0
}
.el-checkbox{
    margin-right:25px;
}
.el-select,.el-cascader{
    display: block !important;
}
.title{
    margin-left: 20px;
}
  .tip {
    color: red;
  }
  .tin_box {
    border: 1px solid #ddd;
    padding: 0 10px 0 10px;
    color:#666;
  }
  .line{
    text-align: center;
  }

  /*上传图片*/
  .thumbnail{
        width: 302px;
        height: 151px;
        border: 1px solid #eee;
        border-radius: 5px;
        display: flex;
        // flex-item-align: center;
    }
    .thumbnail_video{
        padding: 10px;
        width: 340px;
        height: 200px;
        border: 1px solid #eee;
        border-radius: 5px;
        display: flex;
    }

    .thumbnail img{
        width: 100% ;
    }
    .uploadBox{
        width: 100%;
        position: relative;
    }
    .btn_clear{
        position: absolute;
        top: 4px;
        right: 19px;
        padding: 10px 30px;
    }
</style>
